package com.jili.factory;

import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.List;

/**
 *  ClassName: ProxyFactory
 *  Package com.com.jili.factory
 *  Description:
 *  @Author: 廖继礼
 *  @Create: 2025/6/5
 *  @Version: v1.0
 *
 */
public class ProxyFactory {

    public static Object createProxy(Object target, List<Method> beforeAdvice, List<Method> afterAdvice) {
        return Proxy.newProxyInstance(target.getClass().getClassLoader(),
                target.getClass().getInterfaces(),
                (proxy, method, args) -> {
                    // 执行前置通知
                    for (Method advice : beforeAdvice) {
                        advice.invoke(advice.getDeclaringClass().newInstance(), args);
                    }
                    // 执行目标方法
                    Object result = method.invoke(target, args);


                    // 执行后置通知
                    for (Method advice : afterAdvice) {
                        advice.invoke(advice.getDeclaringClass().newInstance(), result);
                    }
                    return result;
                });
    }
}
